#include "Utility.h"

#include "core.h"
#ifdef WIN32
#include <excpt.h>
#endif
#include <QFile>
namespace CoreUtility {
#ifndef NOT_USEQT

QJsonDocument openJsonDoc(const QString& filePath) {
  if (QFile::exists(filePath)) {
    QFile cfgFile(filePath);
    cfgFile.open(QIODevice::ReadOnly);
    QByteArray data = cfgFile.readAll();

    QJsonParseError err;
    QJsonDocument doc(QJsonDocument::fromJson(data, &err));
    if (doc.isNull()) {
      if (err.error == QJsonParseError::IllegalUTF8String) {
        QString string = QString::fromLocal8Bit(data);
        QByteArray bytes = string.toUtf8();
        QJsonDocument docUtf8(QJsonDocument::fromJson(bytes, &err));
        if (!docUtf8.isNull()) {
          doc = docUtf8;
        }
      }
      //	logError(MODULE_NAME, "Dev.cfg parse error! Offset:%d, code:%d,
      //%s ", err.offset, err.error, err.errorString().toUtf8());
    }

    cfgFile.close();
    return doc;
  }
  return QJsonDocument();
}

#endif

int field_copy(char* dest, int capcity, const char* source, int len) {
  // ss_strcpy_s 比ms的strcpy_s快50%,比ms的strcpy慢21%
  int i = 0;
  if (dest && capcity > 0) {
    if (source)  // 即使source为非法值,也会将dest阶段
    {
      if (len == -1) {
        while (*source && i + 1 < capcity) {
          dest[i++] = *source++;
        }
      } else if (len > 0) {
        while (*source && i + 1 < capcity && i < len) {
          dest[i++] = *source++;
        }
      }
      dest[i] = 0;  // 拷贝末尾截断
    }

    dest[capcity - 1] = 0;  // 范围末尾截断
  }
  return i;
}
int field_copyw(wchar_t* dest, int capcity, const wchar_t* source, int len) {
  // ss_strcpy_s 比ms的strcpy_s快50%,比ms的strcpy慢21%
  int i = 0;
  if (dest && capcity > 0) {
    if (source)  // 即使source为非法值,也会将dest阶段
    {
      if (len == -1) {
        while (*source && i + 1 < capcity) {
          dest[i++] = *source++;
        }
      } else if (len > 0) {
        while (*source && i + 1 < capcity && i < len) {
          dest[i++] = *source++;
        }
      }
      dest[i] = 0;  // 拷贝末尾截断
    }

    dest[capcity - 1] = 0;  // 范围末尾截断
  }
  return i;
}

#ifdef WIN32
int qbPrintF(char* const _Buffer, size_t const _BufferCount,
             size_t const _MaxCount, char const* const _Format, ...) {
  int _Result = -1;
  va_list _ArgList;
  __crt_va_start(_ArgList, _Format);

  __try {
    _Result = _vsnprintf_s_l(_Buffer, _BufferCount, _MaxCount, _Format, nullptr,
                             _ArgList);
    if (_Result < 0) _Result = strlen(_Buffer);
  } __except (GetExceptionCode() == ((unsigned long)0xC0000005L)
                  ? EXCEPTION_EXECUTE_HANDLER
                  : EXCEPTION_CONTINUE_SEARCH) {
  }

  __crt_va_end(_ArgList);

  return _Result;
}
#endif

}  // namespace CoreUtility
